package com.sun.handler;

import com.sun.constant.MessageConstant;
import com.sun.exception.BaseException;
import com.sun.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }


    /**
     *
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info("处理SQL异常:{}",ex.getMessage());
        //获取异常对象ex中的错误信息
        String message = ex.getMessage();
        //判断异常信息中是否包含了`Duplicate entry` 数据库中出现了重复的值
        if (message.contains("Duplicate entry")){
            //将包含了错误信息的字符串进行做切割
            String[] s = message.split(" ");
            //lucy
            String username = s[2];
            //拼接错误信息提醒
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR );
    }

}
